#include <mqueue.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>

void signal_handler(int sig)
{
    mq_unlink("/test_mqueue");
    exit(EXIT_SUCCESS);
}

int main(int argc, char const *argv[])
{
    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 1024;
    mqd_t mq = mq_open("/test_mqueue", O_CREAT | O_RDWR, 0644, &attr);

    if (mq < 0)
    {
        perror("mq_open");
    }

    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    pid_t pid = fork();

    if (pid > 0)
    {
        // 父进程
        while (1)
        {
            int result = mq_send(mq, "Hello world!\n", 14, 0);
            sleep(1);
        }
    }
    else if (pid == 0)
    {
        char buf[1024];
        while (1)
        {
            ssize_t msg_len = mq_receive(mq, buf, 1024, 0);
            // printf("消息接收成功\n");
            if (msg_len > 0)
            {
                write(STDOUT_FILENO, buf, msg_len);
            }
        }
    }

    return 0;
}
